package sufutian.com.englishvoicetrans.FireBaseStorage;

import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.File;

/**
 * Created by sufutian on 2017/6/23.
 */

public class FireBaseDemo {

    private UploadTask uploadTask;

    private String TAG = "FireBaseDemo";
    private final StorageReference storageRef;

    private Context context;

    public FireBaseDemo(final Context context) {
        this.context = context;
        FirebaseStorage storage = FirebaseStorage.getInstance();
        storageRef = storage.getReferenceFromUrl("gs://goplay-1201.appspot.com");
        StorageReference audio = storageRef.child("audio");
        StorageReference audioPaigo = audio.child("paigo1.wav");
        String bucket = audioPaigo.getBucket();

        Uri file = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/sufutian" + "/sufutian.wav"));
        StorageReference riversRef = storageRef.child("audio/" + file.getLastPathSegment());
        uploadTask = riversRef.putFile(file);
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Toast.makeText(context, "上传失败", Toast.LENGTH_SHORT).show();
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                Uri downloadUrl = taskSnapshot.getDownloadUrl();
                Toast.makeText(context, "上传云成功" + downloadUrl, Toast.LENGTH_SHORT).show();
            }
        });
    }


    public void deleteFile() {

        StorageReference desertRef = storageRef.child("voice/sufutian.wav");

        // Delete the file
        desertRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show();
            }
        });
    }


}
